<template>
  <div>
    <el-card>
      <el-form ref="form" :model="form" :rules="rules">
        <div class="leftArea">
          <el-form-item>
            <el-upload
              class="upload-demo"
              drag
              :action="uploadFileUrl"
              :accept="accept"
              :file-list="pgForm.fileList"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :headers="headers"
              :show-file-list="false">
<!--              上传列表为空时显示-->
              <div v-if="this.pgForm.fileList.length==0">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </div>
<!--              上传列表不为空，一次只能上传一个-->
              <div v-if="this.pgForm.fileList.length>0">
                <i class="el-icon-circle-check"></i>
                <el-alert
                  :title="form._materialName+fileType"
                  type="success"
                  center
                  :closable="false"
                  show-icon>
                </el-alert>
                <div class="el-upload__text">将文件拖到此处，或<em>点击重新上传</em></div>
              </div>
              <el-collapse class="el-upload__tip" slot="tip">
                <el-collapse-item title="文件大小不超过50M；一次只能上传一个文件；支持格式：">
                  <div>bmp, gif, jpg, jpeg, png, doc, docx, xls, xlsx, ppt, pptx, html, htm, txt, rar, zip, gz, bz2, mp4, avi, rmvb, pdf</div>
                </el-collapse-item>
              </el-collapse>
            </el-upload>
          </el-form-item>
        </div>
        <div class="rightArea">
          <el-form-item label="资料名" prop="_materialName" class="inputArea">
            <el-input v-model="form._materialName" placeholder="请输入资料名" />
          </el-form-item>
          <el-form-item label="资料简介" prop="materialDescription" class="inputArea">
            <el-input v-model="form.materialDescription" type="textarea" :rows="8" placeholder="请输入资料简介" />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {addMaterial} from "@/api/system/material";

export default {
  name: "addMaterial",
  data(){
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      accept:'.bmp,.gif,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.html,.htm,.txt,.rar,.zip,.gz,.bz2,.mp4,.avi,.rmvb,.pdf',
      pgForm: {
        fileList: [],
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 表单参数
      form: {
        materialName: '',
        _materialName: '', // 用一个 materialName 字段的话，点击确定提交后会出现资料名框内容变长的问题，所以加一个__materialName
        materialDescription: ''
      },
      // 表单校验
      rules: {
        _materialName: [
          { required: true, message: "资料名不能为空", trigger: "blur" }
        ],
      },
      suffixStr:'',
      fileType:'',
    }
  },

  methods:{
    //上传文件大小和格式校验
    beforeUpload(file){
      const mimeTypes = {
        'image/bmp': true,
        'image/gif': true,
        'image/jpeg': true,
        'image/png': true,
        'application/msword': true,
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true,
        'application/vnd.ms-excel': true,
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true,
        'application/vnd.ms-powerpoint': true,
        'application/vnd.openxmlformats-officedocument.presentationml.presentation': true,
        'text/html': true,
        'text/plain': true,
        'application/x-rar-compressed': true,
        'application/zip': true,
        'application/x-gzip': true,
        'application/x-bzip2': true,
        'video/mp4': true,
        'video/x-msvideo': true,
        'application/vnd.rn-realmedia-vbr': true,
        'application/pdf': true
      }
      const fileType = file.type.toLowerCase()
      const isAllowedType = mimeTypes[fileType] || false

      if (!isAllowedType) {
        this.$message.error('文件格式不正确')
      }
      const isLt10M = file.size / 1024 / 1024 < 50
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 50MB')
      }
      return isAllowedType && isLt10M
    },

    //上传成功
    handleSuccess(res){
      if(res.code=='200'){
        this.pgForm.fileList.push({
          name: res.newFileName,
          url:  res.fileName
        })
        //自动填充资料名
        this.form._materialName=this.cutString(res.newFileName);
        this.form.storagePath=res.fileName;
        this.fileType=this.getFileType(this.form.storagePath);
        // this.$modal.msgSuccess("上传成功");
      }else {
        this.$modal.msgError("上传失败");
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.storagePath == null) {
            this.$modal.msgError("请先上传文件");
            return;
          }
          //把后缀加上再保存数据库
          this.form.materialName=this.form._materialName+this.suffixStr;
          addMaterial(this.form).then(response => {
            this.$modal.msgSuccess("上传成功");
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        }
        this.pgForm.fileList=[];
      });
    },
    // 取消按钮
    cancel() {
      this.pgForm.fileList=[];
      this.$tab.closeOpenPage();
      this.$router.go(-1);
    },
    //截取字符串
    cutString(str){
      let lastIndex=str.lastIndexOf('_');
      if(lastIndex==-1){
        return str
      }
      this.suffixStr=str.substring(lastIndex);
      return str.substring(0,lastIndex);
    },
    //截取文件后缀
    getFileType(str){
      let suffixIndex=str.lastIndexOf('.');
      if(suffixIndex==-1){
        return ''
      }
      return str.substring(suffixIndex);
    }
  }
}
</script>

<style scoped>

.el-card {
  margin: 40px;
  min-height: 500px;
}
/deep/ .el-form-item{
  width: 90%;
}

/deep/ .el-upload{
  width: 100%;
}
/deep/ .el-upload .el-upload-dragger{
  float: right;
  width: 85%;
  height: 240px;
  border-color: #000;
  margin: 8% 5% 0;

}
.el-upload__tip {
  width: 80%;
  margin: auto;
}
/deep/ .el-collapse-item__header{
  height: 36px;
  line-height: 36px;
}

.leftArea {
  padding: 50px;
  width: 50%;
  float: left;

}
.rightArea {
  width: 50%;
  float: right;
  padding-top: 50px;
}
.inputArea {
  width: 80%;
}
/deep/.el-textarea__inner,/deep/.el-input__inner {
  border-color: #000000;
  border-style: dashed;
}
.dialog-footer {
  text-align: center;
}

.el-icon-finished {
  font-size: 67px;
  color: #2adbbb;
  margin: 40px 0 16px;
  line-height: 50px;
}

.el-alert {
  padding: 0;
  margin: 0;
  background-color: rgba(231,250,240,0);
}


</style>
